<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="子表ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入子表ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="主表ID" prop="masterId">
        <el-input
          v-model="queryParams.masterId"
          placeholder="请输入主表ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物品ID" prop="itemId">
        <el-input
          v-model="queryParams.itemId"
          placeholder="请输入物品ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="RFID编码" prop="rfidCode">
        <el-input
          v-model="queryParams.rfidCode"
          placeholder="请输入RFID编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="显示缺失" prop="showMissing" v-if="queryParams.masterId">
        <el-switch
          v-model="showMissing"
          active-text="显示"
          inactive-text="隐藏"
          @change="handleQuery"
        ></el-switch>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 统计信息和前端搜索 -->
    <el-row :gutter="10" class="mb8" v-if="queryParams.masterId">
      <el-col :span="12" v-if="showMissing">
        <el-alert
          :title="`统计信息：正常记录 ${normalCount} 条，缺失记录 ${missingCount} 条，总计 ${totalRecords} 条`"
          type="info"
          :closable="false">
        </el-alert>
      </el-col>
      <el-col :span="12" v-else>
        <el-alert
          :title="`当前显示：正常记录 ${normalCount} 条`"
          type="success"
          :closable="false">
        </el-alert>
      </el-col>
      <el-col :span="12">
        <el-input
          v-model="frontendSearch"
          placeholder="前端搜索：RFID编码、备注"
          prefix-icon="el-icon-search"
          clearable
          @input="handleFrontendSearch"
          style="width: 100%;">
        </el-input>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:HmzInventoryDetail:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:HmzInventoryDetail:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:HmzInventoryDetail:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:HmzInventoryDetail:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="filteredHmzInventoryDetailList" @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="子表ID" align="center" prop="id" />
      <el-table-column label="主表ID" align="center" prop="masterId" />
      <el-table-column label="物品ID" align="center" prop="itemId" />
      <el-table-column label="RFID编码" align="center" prop="rfidCode">
        <template slot-scope="scope">
          <span :style="scope.row.isMissing ? 'color: red; font-weight: bold;' : ''">
            {{ scope.row.rfidCode }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark">
        <template slot-scope="scope">
          <span :style="scope.row.isMissing ? 'color: red; font-weight: bold;' : ''">
            {{ scope.row.remark }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:HmzInventoryDetail:edit']"
            :disabled="scope.row.isMissing"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:HmzInventoryDetail:remove']"
            :disabled="scope.row.isMissing"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 搜索结果提示 -->
    <div v-if="frontendSearch.trim() && filteredHmzInventoryDetailList.length === 0" class="empty-search-result">
      <el-empty description="未找到匹配的搜索结果" :image-size="80"></el-empty>
    </div>
    
    <!-- 搜索结果统计 -->
    <div v-if="frontendSearch.trim() && filteredHmzInventoryDetailList.length > 0" style="text-align: center; padding: 10px 0; color: #606266;">
      搜索到 {{ filteredHmzInventoryDetailList.length }} 条结果（共 {{ HmzInventoryDetailList.length }} 条数据）
    </div>
    
    <pagination
      v-show="total>0 && !frontendSearch.trim() && !showMissing"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改盘点单子对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="主表ID" prop="masterId">
          <el-input v-model="form.masterId" placeholder="请输入主表ID" />
        </el-form-item>
        <el-form-item label="物品ID" prop="itemId">
          <el-input v-model="form.itemId" placeholder="请输入物品ID" />
        </el-form-item>
        <el-form-item label="RFID编码" prop="rfidCode">
          <el-input v-model="form.rfidCode" placeholder="请输入RFID编码" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listHmzInventoryDetail, getHmzInventoryDetail, delHmzInventoryDetail, addHmzInventoryDetail, updateHmzInventoryDetail } from "@/api/system/HmzInventoryDetail";

export default {
  name: "HmzInventoryDetail",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 盘点单子表格数据
      HmzInventoryDetailList: [],
      // 过滤后的表格数据
      filteredHmzInventoryDetailList: [],
      // 前端搜索关键词
      frontendSearch: '',
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示缺失记录
      showMissing: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        masterId: null,
        itemId: null,
        rfidCode: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  computed: {
    // 正常记录数量
    normalCount() {
      return this.HmzInventoryDetailList.filter(item => !item.isMissing).length;
    },
    // 缺失记录数量
    missingCount() {
      return this.HmzInventoryDetailList.filter(item => item.isMissing).length;
    },
    // 总记录数
    totalRecords() {
      return this.HmzInventoryDetailList.length;
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 前端搜索处理 */
    handleFrontendSearch() {
      if (!this.frontendSearch.trim()) {
        this.filteredHmzInventoryDetailList = [...this.HmzInventoryDetailList];
        return;
      }
      
      const keyword = this.frontendSearch.toLowerCase().trim();
      this.filteredHmzInventoryDetailList = this.HmzInventoryDetailList.filter(item => {
        const rfidCode = (item.rfidCode || '').toLowerCase();
        const remark = (item.remark || '').toLowerCase();
        
        // 只搜索RFID编码和备注，确保精确匹配
        return rfidCode.includes(keyword) || remark.includes(keyword);
      });
    },
    /** 表格行样式 */
    tableRowClassName({row, rowIndex}) {
      if (row.isMissing) {
        return 'missing-row';
      }
      return '';
    },
    /** 查询盘点单子列表 */
    getList() {
      this.loading = true;
      // 构建查询参数，只有当有masterId时才传递showMissing参数
      let params = { ...this.queryParams };
      if (this.queryParams.masterId && this.showMissing) {
        params.showMissing = true;
      }
      
      listHmzInventoryDetail(params).then(response => {
        this.HmzInventoryDetailList = response.rows;
        this.filteredHmzInventoryDetailList = [...response.rows];
        this.total = response.total;
        this.loading = false;
        // 重置前端搜索
        this.frontendSearch = '';
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.frontendSearch = '';
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        masterId: null,
        itemId: null,
        rfidCode: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.showMissing = false;
      this.frontendSearch = '';
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加盘点单子";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getHmzInventoryDetail(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改盘点单子";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateHmzInventoryDetail(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHmzInventoryDetail(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除盘点单子编号为"' + ids + '"的数据项？').then(function() {
        return delHmzInventoryDetail(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/HmzInventoryDetail/export', {
        ...this.queryParams
      }, `HmzInventoryDetail_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
/* 缺失记录行样式 */
::v-deep .missing-row {
  background-color: #fef0f0 !important;
  color: #f56c6c;
}

::v-deep .missing-row:hover {
  background-color: #fde2e2 !important;
}

/* 缺失记录单元格额外样式 */
::v-deep .missing-row td {
  border-color: #f5c6cb !important;
}

/* 空搜索结果样式 */
.empty-search-result {
  padding: 40px 0;
  text-align: center;
  background-color: #fafafa;
  border-radius: 4px;
  margin: 10px 0;
}
</style>
